<?php

class Code {
	//密码字典
	private $dic = array(
			0=>'0',    1=>'1', 2=>'2', 3=>'3', 4=>'4', 5=>'5', 6=>'6', 7=>'7', 8=>'8',
			9=>'9', 10=>'A',  11=>'B', 12=>'C', 13=>'D', 14=>'E', 15=>'F',  16=>'G',  17=>'H',
			18=>'I',19=>'J',  20=>'K', 21=>'L',  22=>'M',  23=>'N', 24=>'O', 25=>'P', 26=>'Q',
			27=>'R',28=>'S',  29=>'T',  30=>'U', 31=>'V',  32=>'W',  33=>'X', 34=>'Y', 35=>'Z'
	);


	public function encodeID($int, $format=8) {
		$dics = $this->dic;
		$dnum = 36; //进制数
		$arr = array ();
		$loop = true;
		while ($loop) {
			$arr[] = $dics[bcmod($int, $dnum)];
			$int = bcdiv($int, $dnum, 0);
			if ($int == '0') {
				$loop = false;
			}
		}
		if (count($arr) < $format)
			$arr = array_pad($arr, $format, $dics[0]);

		return implode('', array_reverse($arr));
	}

	public function decodeID($ids) {
		$dics = $this->dic;
		$dnum = 36; //进制数
		//键值交换
		$dedic = array_flip($dics);
		//去零
		$id = ltrim($ids, $dics[0]);
		//反转
		$id = strrev($id);
		$v = 0;
		for ($i = 0, $j = strlen($id); $i < $j; $i++) {
			$v = bcadd(bcmul($dedic[$id {
				$i }
				], bcpow($dnum, $i, 0), 0), $v, 0);
		}
		return $v;
	}

}

/**
 * 揭晓与插入商品
 * @param $type
 * @param $shop   商品数据
 */
function team_pay_insert_shop($shop='',$type=''){
	$time=sprintf("%.3f",microtime(true)+GOODS_END_TIME);
	if($shop['xsjx_time'] != '0'){
		return aud("UPDATE `@#_teamgoods` SET `canyurenshu`=`zongrenshu`,	`shenyurenshu` = '0' where `id` = '$shop[id]'");
	}
	$tocode = new tocode();
	$tocode->shop = $shop;
	$tocode->team_run_tocode($time,100,$shop['canyurenshu'],$shop);
	$code =$tocode->go_code;
	$content = addslashes($tocode->go_content);
	$counttime = $tocode->count_time;
	//判断是否指定中奖
	if($shop['quyu']){
		$ex_info=query("select * from `@#_member_team_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `uid`='{$shop['quyu']}'");
		$ex_code=explode(",",$ex_info['goucode']);
		$ex_count=count($ex_code);
		$ex_rand=rand(0,$ex_count-1);
		if($ex_code[$ex_rand]){
			$chazhi=$ex_code[$ex_rand]-$code;
			if($chazhi>0)$counttime=$counttime+$chazhi;
			else $counttime=$counttime-abs($chazhi);
			$code=$ex_code[$ex_rand];
			//添加时间校准
			if(!empty($chazhi)){
				$last_info=query("select * from `@#_member_team_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' order by id desc limit 1");
				$time_t_str = str_replace('.','',$last_info['time']);
				$time_str = bcadd($time_t_str,$chazhi);
				$time_arr = str_split($time_str,10);
				$str_t_time = $time_arr[0].'.'.$time_arr[1];
				aud("UPDATE `@#_member_team_record` SET `time`='$str_t_time' where `id` = '{$last_info['id']}'");
				$tocode = new tocode();
				$tocode->shop = $shop;
				$tocode->team_run_tocode($time,100,$shop['canyurenshu'],$shop);
				$content = addslashes($tocode->go_content);
			}
		}
	}

	//如果是一次买满总份数,立即开奖并获取出中奖会员的信息，订单记录信息
	$u_go_info = query("select * from `@#_member_team_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `goucode` LIKE  '%$code%'");
	$u_info = query("select uid,username,email,mobile,img from `@#_member` where `uid` = '$u_go_info[uid]'");

	//更新商品
	$query = true;
	if($u_info){
		$u_info['username'] = _htmtocode($u_info['username']);
		$q_user = serialize($u_info); //序列化中奖会员信息
		//获取system.inc.php设置的2分钟倒计时
		$gtimes = GOODS_END_TIME;
		if($gtimes == 0 || $gtimes == 1){
			$q_showtime = 'N'; //无动画开奖
		}else{
			$q_showtime = 'Y';  //显示动画开奖
		}
		$sqlss = "UPDATE `@#_teamgoods` SET
		`canyurenshu`=`zongrenshu`,
		`shenyurenshu` = '0',
		`q_uid` = '$u_info[uid]',
		`q_user` = '$q_user',
		`q_user_code` = '$code',
		`q_content`	= '$content',
		`q_counttime` ='$counttime',
		`q_end_time` = '$time',
		`q_showtime` = '$q_showtime'
		where `id` = '$shop[id]'";
		//file_put_contents("team.sql",$sqlss);
		$q = aud($sqlss);
		if(!$q){
			$query = false;
		}
		if($q){
			$q = aud("UPDATE `@#_member_team_record` SET `huode` = '$code' where `id` = '$u_go_info[id]' and `code` = '$u_go_info[code]' and `uid` = '$u_go_info[uid]' and `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]'");
			if(!$q) {
				$query = false;
			}else{
				$post_arr= array("uid"=>$u_info['uid'],"gid"=>$shop['id'],"send"=>1);
				_g_triggerRequest(WEB_PATH.'/app.php?act=t_send_shop_code',false,$post_arr);
			}
		}else{
			$query =  false;
		}
	}else{
		$query =  false;
	}

	if ($query == false && $type == 'add'){
		if($shop['qishu'] < $shop['maxqishu']){
			$maxinfo = query("select * from `@#_teamgoods` where `sid` = '$shop[sid]' order by `qishu` DESC LIMIT 1");
			if(!$maxinfo){
				$maxinfo=array("qishu"=>$shop['qishu']);
			}
			$intall = team_content_add_shop_install($maxinfo,false);
			if(!$intall) return $query;
		}
	}
	return $query;
}

/**
 新建一期商品
info 	 商品的ID 或者 商品的数组
使用此函数注意传进来的的商品期数不等于最大期数
autocommit @是否开启事物
*/
function team_content_add_shop_install($info=null,$autocommit=true){
	$model = new CoreModel();
	if($autocommit){
		$model->startTrans();
	}
	unset($info['id']);
	unset($info['q_uid']);
	unset($info['q_user']);
	unset($info['q_user_code']);
	unset($info['q_content']);
	unset($info['q_counttime']);
	unset($info['q_end_time']);
	unset($info['q_create_uid']);
	unset($info['q_group_name']);
	unset($info['q_create_time']);
	unset($info['q_create_pwd']);

	$info['xsjx_time']=0;
	$info['time'] = time();
	$info['qishu'] = intval($info['qishu']);
	$info['qishu']++;
	$info['canyurenshu'] = '0';
	$info['shenyurenshu'] = $info['zongrenshu'];
	$info['codes_table'] = t_content_get_codes_table();
	$info['q_showtime']= 'N';
	$info['title'] = _htmtocode($info['title']);
	$info['title2'] = _htmtocode($info['title2']);

	$keys  = $vals = '(';
	foreach($info as $key=>$val){
		$keys.="`$key`,";
		$vals.="'$val',";
	}
	$keys = rtrim($keys,',');
	$vals = rtrim($vals,',');
	$keys.= ')';
	$vals.= ')';
	$sql = "INSERT INTO `@#_teamgoods` ".$keys." VALUES ".$vals;
	$q1 = aud($sql);
	$id = $model->getLastInsID();
	$q2 = t_content_get_go_codes($info['zongrenshu'],3000,$id);
	if($autocommit){
		if($q1 && $q2){
			$model->commit();
			return true;
		}else{
			$model->rollback();
			return false;
		}
	}else{
		if($q1 && $q2){
			return true;
		}else{
			return false;
		}
	}
}

//创团复制
function team_content_add_shop_install2($info=null,$autocommit=true){
	$model = new CoreModel();
	if($autocommit){
		$model->startTrans();
	}
	unset($info['id']);
	unset($info['q_uid']);
	unset($info['q_user']);
	unset($info['q_user_code']);
	unset($info['q_content']);
	unset($info['q_counttime']);
	unset($info['q_end_time']);
	unset($info['cart_gorenci']);
	unset($info['cart_xiaoji']);
	unset($info['cart_shenyu']);

	$info['xsjx_time']=0;
	$info['time'] = time();
	$info['qishu'] = intval($info['qishu']);
	$info['qishu']++;
	$info['canyurenshu'] = '0';
	$info['shenyurenshu'] = $info['zongrenshu'];
	$info['codes_table'] = t_content_get_codes_table();
	$info['q_showtime']= 'N';
	$info['title'] = _htmtocode($info['title']);
	$info['title2'] = _htmtocode($info['title2']);
	$info['q_create_pwd'] = team_pay_get_dingdan_code(); //生成组团密码
	$info['q_create_time'] = time();

	$keys  = $vals = '(';
	foreach($info as $key=>$val){
		$keys.="`$key`,";
		$vals.="'$val',";
	}
	$keys = rtrim($keys,',');
	$vals = rtrim($vals,',');
	$keys.= ')';
	$vals.= ')';

	$sql = "INSERT INTO `@#_teamgoods` ".$keys." VALUES ".$vals;

	$q1 = aud($sql);
	$id = $model->getLastInsID();

	$q2 = t_content_get_go_codes($info['zongrenshu'],3000,$id);
	if($autocommit){
		if($q1 && $q2){
			$model->commit();
			return $id;
		}else{
			$model->rollback();
			return false;
		}
	}else{
		if($q1 && $q2){
			return $id;
		}else{
			return false;
		}
	}
}


/*
 生成夺宝码
CountNum @ 生成个数
len 	    @ 生成长度
sid	    @ 商品ID
*/
function t_content_get_go_codes($CountNum=null,$len=null,$sid=null){
	$table = query("SELECT * from `@#_caches` where `key` = 'teamcodes_table' LIMIT 1");
	$table = '@#_teamcodes_'.$table['value'];

	$num = ceil($CountNum/$len);
	$code_i = $CountNum;

	//$CountNum 小于3000时执行
	if($num == 1){
		$codes=array();
		for($i=1;$i<=$CountNum;$i++){
			$codes[$i]=10000000+$i;
		}
		shuffle($codes);
		$codes = serialize($codes);
		$query = aud("INSERT INTO `$table` (`s_id`, `s_cid`, `s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '1','$CountNum','$codes','$codes')");
		unset($codes);
		return $query;
	}

	$query_1 = true;
	// $num = 2; 100
	for($k=1;$k<$num;$k++){
		$codes=array();
		for($i=1;$i<=$len;$i++){
			$codes[$i] = 10000000+$code_i;
			$code_i--;
		}
		shuffle($codes);
		$codes=serialize($codes);
		$query_1 = aud("INSERT INTO `$table` (`s_id`, `s_cid`, `s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '$k','$len','$codes','$codes')");
		unset($codes);
	}

	$CountNum = $CountNum -(($num-1)*$len);
	$codes=array();

	for($i=1;$i<=$CountNum;$i++){
		$codes[$i]=10000000+$code_i;
		$code_i--;
	}
	shuffle($codes);
	$codes=serialize($codes);
	$query_2 = aud("INSERT INTO `$table` (`s_id`, `s_cid`,`s_len`, `s_codes`,`s_codes_tmp`) VALUES ('$sid', '$num','$CountNum','$codes','$codes')");
	unset($codes);
	return $query_1 && $query_2;
}

/*
 计算夺宝码表
*/
function t_content_get_codes_table(){
	$num = query("SELECT * from `@#_caches` where `key` = 'teamcodes_table' LIMIT 1");
	$table = 'teamcodes_'.$num['value'];
	$shopcodes_table = query("SHOW TABLE STATUS LIKE '@#_$table'");

	if(!$shopcodes_table || !$num) return false;
	if($shopcodes_table['Auto_increment'] >= 99999){
		$num = intval($num['value'])+1;
		$shopcodes_table = 'teamcodes_'.$num;
		$q1 = aud("
				CREATE TABLE `@#_$shopcodes_table` (
				`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
				`s_id` int(10) unsigned NOT NULL,
				`s_cid` smallint(5) unsigned NOT NULL,
				`s_len` smallint(5) DEFAULT NULL,
				`s_codes` text,
				`s_codes_tmp` text,
				PRIMARY KEY (`id`),
				KEY `s_id` (`s_id`),
				KEY `s_cid` (`s_cid`),
				KEY `s_len` (`s_len`)
		) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
				");
		$q2 = aud("UPDATE `@#_caches` SET `value` = '$num' where `key` = 'teamcodes_table'");
		if(!$q1 || !$q2)return false;
	}else{
		$num = intval($num['value']);
		$shopcodes_table = 'teamcodes_'.$num;
	}
	return $shopcodes_table;
}


/*
*   生成购买的抢购码
*	user_num 		@生成个数	如果购买1个，生成一个抢购码
*	shopinfo		@商品信息	商品订单信息
*	ret_data		@返回信息
*/
function pay_get_shop_codes($user_num=1,$shopinfo=null,&$ret_data=null){
		$ret_data['query'] = true;
		$table = '@#_'.$shopinfo['codes_table'];
		$codes_arr = array();
		
		//取出最后一条
		$codes_one = query("select id,s_id,s_cid,s_len,s_codes from `$table` where `s_id` = '$shopinfo[id]' order by `s_cid` DESC  LIMIT 1 for update");
		
		$codes_arr[$codes_one['s_cid']] = $codes_one;
		$codes_count_len = $codes_arr[$codes_one['s_cid']]['s_len'];
		
		//如果剩余抢购码长 小于 购物长度
		if($codes_count_len < $user_num && $codes_one['s_cid'] > 1){
			for($i=$codes_one['s_cid']-1;$i>=1;$i--):
				$codes_arr[$i] = query("select id,s_id,s_cid,s_len,s_codes from `$table` where `s_id` = '$shopinfo[id]' and `s_cid` = '$i'  LIMIT 1 for update");
				$codes_count_len += $codes_arr[$i]['s_len'];
				if($codes_count_len > $user_num)  break;
			endfor;
		}

		if($codes_count_len < $user_num) $user_num = $codes_count_len;

		$ret_data['user_code'] = '';
		$ret_data['user_code_len'] = 0;

		foreach($codes_arr as $icodes){
			$u_num = $user_num;
			$icodes['s_codes'] = unserialize($icodes['s_codes']);
			$code_tmp_arr = array_slice($icodes['s_codes'],0,$u_num);
			$ret_data['user_code'] .= implode(',',$code_tmp_arr);
			$code_tmp_arr_len = count($code_tmp_arr);

			if($code_tmp_arr_len < $u_num){
				$ret_data['user_code'] .= ',';
			}

			$icodes['s_codes'] = array_slice($icodes['s_codes'],$u_num,count($icodes['s_codes']));
			$icode_sub = count($icodes['s_codes']);
			$icodes['s_codes'] = serialize($icodes['s_codes']);

			if(!$icode_sub){
				$query = aud("UPDATE `$table` SET `s_cid` = '0',`s_codes` = '$icodes[s_codes]',`s_len` = '$icode_sub' where `id` = '$icodes[id]'");
				if(!$query)$ret_data['query'] = false;
			}else{
				$query = aud("UPDATE `$table` SET `s_codes` = '$icodes[s_codes]',`s_len` = '$icode_sub' where `id` = '$icodes[id]'");
				if(!$query)$ret_data['query'] = false;
			}
			$ret_data['user_code_len'] += $code_tmp_arr_len;
			$user_num  = $user_num - $code_tmp_arr_len;
		}

}

//进团佣金
/**
 * 组团不满人 不开奖，佣金和购买商品金额全部需退回
 * @param string $uid
 * @param string $dingdancode
 * @return boolean
 */
function team_pay_go_yongjin($uid=null,$dingdancode=null){
	if(!$uid || !$dingdancode)return true;
	$time=time();
// 	$config = include ROOT_PATH.'/core/config/user_fufen.ini.php';
	$config = include INC_PATH.'/member/lib/user_fufen.ini.php';

	$yesyaoqing=query("SELECT `yaoqing`,`agentyaoqing` FROM `@#_member` WHERE `uid`='$uid'");
	$gorecode=query("SELECT * FROM `@#_member_team_record` WHERE `code`='$dingdancode'",2);

	if ($yesyaoqing['agentyaoqing']){
		$agent_id = $yesyaoqing['agentyaoqing'];
		$level_id = M('Member')->where(array('uid' => $agent_id))->getField('level_id');
		$level_info = M('agent_level')->where(array('id' => $level_id))->find();
		$bl = floatval(substr(sprintf("%.3f",$level_info['baifenbi']), 0, -1));
		foreach($gorecode as $val){
			$y_money = $val['moneycount'] * $bl;
			$content ="(参团)".$val['shopname'];
			aud("INSERT INTO `@#_member_agent_recodes`(`uid`,`agent_id`,`type`,`content`,`shopid`,`money`,`ygmoney`,`bl`,`time`)VALUES('$uid','$agent_id','1','$content','$val[shopid]','$y_money','$val[moneycount]','$bl','$time' )");
		}
	}

	if($yesyaoqing['yaoqing']){
		$yongjin = $config['fufen_yongjin']; //每一元返回的佣金
	}else{
		return true;
	}
	$yongjin = floatval(substr(sprintf("%.3f",$yongjin), 0, -1));

	foreach($gorecode as $val){
		$y_money2 = $val['moneycount'] * $yongjin;
		$content="(参团)".$val['shopname'];
		aud("INSERT INTO `@#_member_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`buytype`,`time`)VALUES('$uid','1','$content','$val[shopid]','$y_money2','$val[moneycount]','1','$time')");
	}
	
	//===========start
	$shareSet=query("SELECT * from `@#_shareagentbili` where id=1 ");
	if($shareSet['status']==1){
		$bili = explode('|',$shareSet['shareAgentBili']);
	
		//  $a = explode('|',$pl);
		$userinfo = query("SELECT uid,username,mobile,yaoqing from `@#_member`",2);
		$yaoqinginfo =  getMenuTree($userinfo,$yesyaoqing['yaoqing'],0,$shareSet['level']);
		$time=time();
	
		// $b=$a;
		foreach($yaoqinginfo as $ykey=>$value){
			foreach($gorecode as $key=>$val){
				$y_money=$val['moneycount'] * $bili[$ykey];
				$content="(第".$val['shopqishu']."期)".$val['shopname'];
				$add[$ykey][$key]='用户'.$value['uid'].'|收到：'.$uid.'购买了'.$val['moneycount'].'|'.(float)$bili[$ykey].'|收入佣金：'.(float)$val['moneycount']*($bili[$ykey]/100).'|商品：'.$content.'|'.$val['shopid'].'|'.$y_money.'|'.$val['moneycount'].'|'.$time;
				$inset =$add[$ykey][$key];
				$aid = $value['uid'];
				$level =$value['level'];
				$moneycount = $val['moneycount'];
				$agent_bili      = $bili[$ykey];
				$shopid       = $val['shopid'];
				$price       =round((float)$val['moneycount']*($bili[$ykey]/100),2);
				if((float)($bili[$ykey]/100)>0){
	
					$dss = aud("INSERT INTO `@#_text_log`(`conntet`)VALUES('$inset')");
					$rr = aud("INSERT INTO `@#_distribution_log`(`orderid`,`uid`,`level`,`shop_type`,`shop_price`,`cid`,`time`,`bili`,`gain_price`,`shopid`,`shop_content`,`status`)VALUES('$dingdancode','$aid','$level','1','$moneycount','$uid','$time','$agent_bili','$price','$shopid','$content','0')");
	
				}
	
			}

		}
	
		$teamGoodsInfo=query("SELECT * FROM `@#_member_team_record` WHERE `code`='$dingdancode'");
	
		$teamGoodsInfo['shopqishu'];
		$shopid=$teamGoodsInfo['shopid'];
		$shopqishu= $teamGoodsInfo['shopqishu'];
		$checkTeam  = query("SELECT * FROM `@#_teamgoods` where `id`='$shopid' and `qishu`='$shopqishu' ");
		if($checkTeam['shenyurenshu']==0){
	
			$res = aud("UPDATE `@#_distribution_log` SET `status`='1' WHERE `shopid`='{$checkTeam['id']}' and `shop_type`='1' and `status`=0 ");
	
		}
	
	}
	//========end
}

//生成订单号  100000000
function pay_get_dingdan_code($dingdanzhui=''){
	return $dingdanzhui.time().substr(microtime(),2,6).rand(0,9);
}

//生成夺宝邀请码  3920CZXE66
function team_pay_get_dingdan_code($dingdanzhui=''){
//  $code = new Code();
// 	$card_no = $code->encodeID(mt_rand(100000,999999),5);
// 	$card_pre = mt_rand(100, 999);
// 	$card_vc = substr(md5($card_pre.$card_no),0,2);
// 	$card_vc = strtoupper($card_vc);
// 	return $card_pre.$card_no.$card_vc;

	return substr(microtime(),2,5).rand(0,9);
}

/**
 * 揭晓商品
 * @param $type
 * @param $shop   商品数据
 */
function team_pay_no_insert_shop($shop='',$type=''){
	$time=sprintf("%.3f",microtime(true)+GOODS_END_TIME);
	if($shop['xsjx_time'] != '0'){
		return aud("UPDATE `@#_teamgoods` SET `canyurenshu`=`zongrenshu`,	`shenyurenshu` = '0' where `id` = '$shop[id]'");
	}

	//时时彩开奖码
	$time_time_data = autumn_getcode();
	if (!is_array($time_time_data)){
		$time_time_data = array('opentime' => '','opencode' => 00000);
	}

	$tocode = new tocode();
	$tocode->shop = $shop;
	$tocode->shishi_cai = $time_time_data;
	$tocode->team_run_tocode($time,100,$shop['canyurenshu'],$shop);

	$code =$tocode->go_code;
	$counttime = $tocode->count_time;
	$content = addslashes($tocode->go_content);

	//2015-12-21修改，判断是否指定中奖//
	if($shop['quyu']){
		$ex_info=query("select * from `@#_member_team_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `uid`='{$shop['quyu']}'");
		$ex_code=explode(",",$ex_info['goucode']);
		$ex_count=count($ex_code);
		$ex_rand=rand(0,$ex_count-1);
		if($ex_code[$ex_rand]){
			$chazhi=$ex_code[$ex_rand]-$code;
			if($chazhi>0)$counttime=$counttime+$chazhi;
			else $counttime=$counttime-abs($chazhi);
			$code=$ex_code[$ex_rand];

			//添加时间校准
			if(!empty($chazhi)){
				$last_info=query("select * from `@#_member_team_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' order by id desc limit 1");
				$time_t_str = str_replace('.','',$last_info['time']);
				$time_str = bcadd($time_t_str,$chazhi);
				$time_arr = str_split($time_str,10);
				$str_t_time = $time_arr[0].'.'.$time_arr[1];
				aud("UPDATE `@#_member_team_record` SET `time`='$str_t_time' where `id` = '{$last_info['id']}'");
				$tocode->shop = $shop;
				$tocode->team_run_tocode($time,100,$shop['canyurenshu'],$shop);
				$content = addslashes($tocode->go_content);
			}
		}
	}

	//如果是一次买满总份数,立即开奖并获取出中奖会员的信息，订单记录信息
	$u_go_info = query("select * from `@#_member_team_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `goucode` LIKE  '%$code%'");
	$u_info = query("select uid,username,email,mobile,img from `@#_member` where `uid` = '$u_go_info[uid]'");

	//更新商品
	$query = true;
	if($u_info){
		$u_info['username'] = _htmtocode($u_info['username']);
		$q_user = serialize($u_info); //序列化中奖会员信息
		//获取system.inc.php设置的2分钟倒计时
		$gtimes = GOODS_END_TIME;
		if($gtimes == 0 || $gtimes == 1){
			$q_showtime = 'N'; //无动画开奖
		}else{
			$q_showtime = 'Y';  //显示动画开奖
		}
		$sqlss = "UPDATE `@#_teamgoods` SET
		`canyurenshu`=`zongrenshu`,
		`shenyurenshu` = '0',
		`q_uid` = '$u_info[uid]',
		`q_user` = '$q_user',
		`q_user_code` = '$code',
		`q_content`	= '$content',
		`q_counttime` ='$counttime',
		`q_end_time` = '$time',
		`q_showtime` = '$q_showtime',
		`opencode` = '{$time_time_data['opencode']}',
		`opentime` = '{$time_time_data['opentime']}'
		where `id` = '$shop[id]'";
		$q = aud($sqlss);

		if(!$q){
			$query = false;
		}

		if($q){
			$q = aud("UPDATE `@#_member_team_record` SET `huode` = '$code' where `id` = '$u_go_info[id]' and `code` = '$u_go_info[code]' and `uid` = '$u_go_info[uid]' and `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]'");
			if(!$q) {
				$query = false;
			}else{
				$post_arr= array("uid"=>$u_info['uid'],"gid"=>$shop['id'],"send"=>1);
				_g_triggerRequest(WEB_PATH.'/app.php?act=t_send_shop_code',false,$post_arr);
			}
		}else{
			$query =  false;
		}

	}else{
		$query =  false;
	}

	return $query;
}

/*
	揭晓与插入商品
	@shop   商品数据
*/
function pay_insert_shop($shop='',$type=''){
	$time=sprintf("%.3f",microtime(true)+GOODS_END_TIME);
	if($shop['xsjx_time'] != '0'){
		return aud("UPDATE `@#_shoplist` SET `canyurenshu`=`zongrenshu`,	`shenyurenshu` = '0' where `id` = '$shop[id]'");
	}
	
	//时时彩开奖码
	$time_time_data = autumn_getcode();
	if (!is_array($time_time_data)){
		$time_time_data = array('opentime' => '','opencode' => 00000);
	}
	
	$tocode = new tocode();
	$tocode->shop = $shop;
	$tocode->shishi_cai = $time_time_data;
	$tocode->run_tocode($time,100,$shop['canyurenshu'],$shop);

	$code = $tocode->go_code;
	$counttime = $tocode->count_time;
 	$content = addslashes($tocode->go_content);
	
	//判断是否指定中奖//
	if($shop['quyu']){
		$ex_info= query("select * from `@#_member_go_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `uid`='{$shop['quyu']}'");
	    $ex_code=explode(",",$ex_info['goucode']);
		$ex_count=count($ex_code);
		$ex_rand=rand(0,$ex_count-1);
		if($ex_code[$ex_rand]){
			$chazhi=$ex_code[$ex_rand]-$code;
			if($chazhi>0){
				$counttime=$counttime+$chazhi;
			}else{
				$counttime=$counttime-abs($chazhi);
			}
			$code=$ex_code[$ex_rand];
			
			//添加时间校准
			if(!empty($chazhi)){
				$last_info=query("select * from `@#_member_go_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' order by id desc limit 1");
				$time_t_str = str_replace('.','',$last_info['time']);
				$time_str = bcadd($time_t_str,$chazhi);
				$time_arr = str_split($time_str,10);
				$str_t_time = $time_arr[0].'.'.$time_arr[1];
				aud("UPDATE `@#_member_go_record` SET `time`='$str_t_time' where `id` = '{$last_info['id']}'");

				$tocode = new tocode();
				$tocode->shop = $shop;
				$tocode->run_tocode($time,100,$shop['canyurenshu'],$shop);
				$content = addslashes($tocode->go_content);
			}
		}
	}

	$u_go_info = query("select * from `@#_member_go_record` where `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]' and `goucode` LIKE  '%$code%'");
	$u_info = query("select uid,username,email,mobile,img from `@#_member` where `uid` = '$u_go_info[uid]'");

	//更新商品
	$query = true;
	if($u_info){
		$u_info['username'] = _htmtocode($u_info['username']);
		$q_user = serialize($u_info);
		$gtimes = GOODS_END_TIME;
		if($gtimes == 0 || $gtimes == 1){
			$q_showtime = 'N';
		}else{
			$q_showtime = 'Y';
		}
		$sqlss = "UPDATE `@#_shoplist` SET
							`canyurenshu`=`zongrenshu`,
							`shenyurenshu` = '0',
							`q_uid` = '$u_info[uid]',
							`q_user` = '$q_user',
							`q_user_code` = '$code',
							`q_content`	= '$content',
							`q_counttime` ='$counttime',
							`q_end_time` = '$time',
							`opencode` = '{$time_time_data['opencode']}',
							`opentime` = '{$time_time_data['opentime']}',
							`q_showtime` = '$q_showtime'
							 where `id` = '$shop[id]'";

		$q = aud($sqlss);
		if(!$q)$query = false;

		if($q){
			$q = aud("UPDATE `@#_member_go_record` SET `huode` = '$code' where `id` = '$u_go_info[id]' and `code` = '$u_go_info[code]' and `uid` = '$u_go_info[uid]' and `shopid` = '$shop[id]' and `shopqishu` = '$shop[qishu]'");
			if(!$q) {
				$query = false;
			}else{
				$post_arr= array("uid"=>$u_info['uid'],"gid"=>$shop['id'],"send"=>1);
				_g_triggerRequest(WEB_PATH.'/app.php?act=send_shop_code',false,$post_arr);
			}
		}else{
			$query =  false;
		}
	}else{
		$query =  false;
	}

	/******************************/


	/*新建*/
	if($query){
		if($shop['qishu'] < $shop['maxqishu']){
			$maxinfo = query("select * from `@#_shoplist` where `sid` = '$shop[sid]' order by `qishu` DESC LIMIT 1");
			file_put_contents('goods.txt', var_export($maxinfo,true));
			if(!$maxinfo){
				$maxinfo=array("qishu"=>$shop['qishu']);
			}
			$intall = content_add_shop_install($maxinfo,false);
			if(!$intall) return $query;
		}
	}
	return $query;
}

/*
	抢购基金
	go_number @抢购人次
*/
function pay_go_fund($go_number=null){
	if(!$go_number)return true;
	$fund = query("select * from `@#_fund` where 1");
	if($fund && $fund['fund_off']){
		$money = $fund['fund_money'] * $go_number + $fund['fund_count_money'];
		return aud("UPDATE `@#_fund` SET `fund_count_money` = '$money'");
	}else{
		return true;
	}
}


/*
	用户佣金
	uid 		用户id
	dingdancode	@订单号
*/
function pay_go_yongjin($uid=null,$dingdancode=null){
	if(!$uid || !$dingdancode)return true;
	$time=time();
	//福分/经验/佣金
// 	$config = include ROOT_PATH.'/core/config/user_fufen.ini.php';
	$config = include INC_PATH.'/member/lib/user_fufen.ini.php';
	$yesyaoqing=query("SELECT `yaoqing`,`agentyaoqing` FROM `@#_member` WHERE `uid`='$uid'");
	$gorecode=query("SELECT * FROM `@#_member_go_record` WHERE `code`='$dingdancode'",2);

	if ($yesyaoqing['agentyaoqing']){
		$agent_id = $yesyaoqing['agentyaoqing'];
		$level_id = M('Member')->where(array('uid' => $agent_id))->getField('level_id');
		$level_info = M('agent_level')->where(array('id' => $level_id))->find();
		$bl = floatval(substr(sprintf("%.3f",$level_info['baifenbi']), 0, -1));
		foreach($gorecode as $val){
			$y_money=$val['moneycount'] * $bl;
			$content="(第".$val['shopqishu']."期)".$val['shopname'];
			aud("INSERT INTO `@#_member_agent_recodes`(`uid`,`agent_id`,`type`,`content`,`shopid`,`money`,`ygmoney`,`bl`,`time`)VALUES('$uid','$agent_id','1','$content','$val[shopid]','$y_money','$val[moneycount]','$bl','$time' )");
		}
	}
	
	//=============================================start
	if($yesyaoqing['yaoqing']){
		$yongjin=$config['fufen_yongjin']; //每一元返回的佣金
	}else{
		return true;
	}
	$yongjin = floatval(substr(sprintf("%.3f",$yongjin), 0, -1));
	foreach($gorecode as $val){
		$y_money=$val['moneycount'] * $yongjin;
		$content="(第".$val['shopqishu']."期)".$val['shopname'];
		aud("INSERT INTO `@#_member_recodes`(`uid`,`type`,`content`,`shopid`,`money`,`ygmoney`,`time`)VALUES('$uid','1','$content','$val[shopid]','$y_money','$val[moneycount]','$time' )");
	}
	//==============================================end
	
	
	$shareSet=query("SELECT * from `@#_shareagentbili` where id=1");
	
	if($shareSet['status']==1){

		$bili = explode('|',$shareSet['shareAgentBili']);
		$userinfo = query("SELECT uid,username,mobile,yaoqing from `@#_member`",2);
		$yaoqinginfo =  getMenuTree($userinfo,$yesyaoqing['yaoqing'],0,$shareSet['level']);
		$time=time();

		foreach($yaoqinginfo as $ykey=>$value){
			foreach($gorecode as $key=>$val){
				$y_money=round($val['moneycount'] * $bili[$ykey],2);
				$content="(第".$val['shopqishu']."期)".$val['shopname'];
				$add[$ykey][$key]='用户'.$value['uid'].'|收到：'.$uid.'购买了'.$val['moneycount'].'|'.(float)$bili[$ykey].'|收入佣金：'.(float)$val['moneycount']*($bili[$ykey]/100).'|商品：'.$content.'|'.$val['shopid'].'|'.$y_money.'|'.$val['moneycount'].'|'.$time;
				$inset =$add[$ykey][$key];
				$aid = $value['uid'];
				$level =$value['level'];
				$moneycount = round($val['moneycount'],2);
				$agent_bili      = $bili[$ykey];
				$shopid       = $val['shopid'];
				$price       =round((float)$val['moneycount']*($bili[$ykey]/100),2);
				if((float)($bili[$ykey]/100)>0){
					$dss = aud("INSERT INTO `@#_text_log`(`conntet`)VALUES('$inset')");
					$rr = aud("INSERT INTO `@#_distribution_log`(`orderid`,`uid`,`level`,`shop_type`,`shop_price`,`cid`,`time`,`bili`,`gain_price`,`shopid`,`shop_content`,`status`)VALUES('$dingdancode','$aid','$level','0','$moneycount','$uid','$time','$agent_bili','$price','$shopid','$content','1')");
	
				}
	
			}
		}
	}
	
	
}


function getMenuTree($arrCat,$parent_id = 0,$level = 0,$agentLevel = 0){
	static  $arrTree = array(); //使用static代替global
	if( empty($arrCat)){ return FALSE;}
	$level++;
	foreach($arrCat as $key => $value)
	{
		//if($value['partnerId'] == $parent_id)
		if($value['uid'] == $parent_id)
		{
			$value['level'] = $level;
			$arrTree[] = $value;
			unset($arrCat[$key]); //注销当前节点数据，减少已无用的遍历
			if($level<$agentLevel){
				getMenuTree($arrCat,$value['yaoqing'],$level,$agentLevel);
			}

		}
	}

	return $arrTree;
}

?>